package com.lxd.milktea.controller;


import com.lxd.milktea.VO.ResultVO;
import com.lxd.milktea.dataobject.OrderDetail;
import com.lxd.milktea.dto.OrderDTO;
import com.lxd.milktea.service.OrderService;
import com.lxd.milktea.util.DateUtil;
import com.lxd.milktea.util.ResultVOUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 1. 参数检验
     * 2. 查询商品信息(调用商品服务)
     * 3. 计算总价
     * 4. 扣库存(调用商品服务)
     * 5. 订单入库
     */
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@RequestBody List<OrderDetail> orderDetails) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderDetailList(orderDetails);
        OrderDTO result = orderService.create(orderDTO);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());
        return ResultVOUtil.success(map);
    }
    /**
     * 查询所有的订单
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public ResultVO list(@RequestParam(value = "page",defaultValue = "1")Integer page, @RequestParam(value = "size",defaultValue = "10")Integer size, Map<String,Object> map){
        PageRequest pageRequest = PageRequest.of(page-1,size);
        Page<OrderDTO> list = orderService.findList(pageRequest);
        map.put("orderDTOPage",list);
        map.put("currentPage",page);
        map.put("pageSize",size);
        return ResultVOUtil.success(map);
    }


    /**
     * 查看订单详情
     * @param orderId
     * @return
     */
    @GetMapping("/detail")
    public ResultVO<OrderDTO> detail(@RequestParam("orderId")String orderId){
        OrderDTO orderOne = orderService.findOne(orderId);
        return ResultVOUtil.success(orderOne);
    }

    @GetMapping("/count")
    @ResponseBody
    @ApiOperation("获取产品数量统计")
    public ResultVO count(){
        Long aLong = DateUtil.monthTimeInMillis();
        Timestamp t = new Timestamp(aLong);
        //获取本月初到现在的产品订单
        List<OrderDetail> listByDate = orderService.findListByDate(t);
        //处理数据
        HashMap<String,Integer> ids = new HashMap<>();
        listByDate.stream()
                .forEach(orderDetail -> {
                    String productName = orderDetail.getProductName();
                    int productQuantity = orderDetail.getProductQuantity();
                    ids.merge(productName,productQuantity,(oldVal,newVal)-> oldVal+newVal);
                });
        return ResultVOUtil.success(ids);
    }

}
